import { GoodItem, sprite } from '@/utils/myinterface';
import { Grid, GridItem, Toast } from 'react-vant';
import { ShopO } from '@react-vant/icons';
import { connect } from 'dva';
import { useEffect, useState } from 'react';
import { changeGoods } from '@/utils/utils/index';
export default connect(({ index }) => index)((props) => {
  const [goods, setGoods] = useState<Array<GoodItem> | null>(null);

  useEffect(() => {
    setGoods(props.goods);
    // console.log("goods", props.goods)
  }, []);
  /**
   * 状态点击按钮
   * @param item
   * @returns
   *
   */
  const statsuReturnFn = (item: GoodItem) => {
    let hp = item.attr.hp || 0;
    let pp = item.attr?.pp || 0;
    let currHp = props.curSprite.attr.currAttr.hp;
    let maxHp = props.curSprite.attr.maxAttr.hp;

    //驳回
    if (item.size <= 0) return Toast({ message: `${item.name}数量不足` });
    if (hp && props.curSprite && currHp == maxHp)
      return Toast({ message: '精灵状态已为最佳' });

    const newgoods = changeGoods(goods, item.name, -1);
    setGoods([...newgoods]);
    props.dispatch({
      type: 'index/saveGoods',
      payload: goods,
    });

    let newcursprite = JSON.parse(JSON.stringify(props.curSprite));
    //pp
    if (!!pp) {
      newcursprite.skill = newcursprite.skill.map((item) => ({
        ...item,
        count: item.count + pp > item.size ? item.size : item.count + pp,
      }));
    }
    //血量
    if (!!hp) {
      let curHp = hp > maxHp - currHp ? maxHp : currHp + hp;
      newcursprite.attr.currAttr.hp = curHp;
    }

    //赋值并存档
    props.setCurSprite(newcursprite);
    const newspriteArry =
      props.spriteArry &&
      props.spriteArry.map((it: sprite) => {
        if (props.curSprite && it.name == props.curSprite.name) {
          return {
            ...it,
            ...props.curSprite,
          };
        }
        return it;
      });
    props.dispatch({ type: 'index/saveSpriteArry', payload: newspriteArry });
    Toast({ message: '你使用了' + item.name });
    props.changeCurRound('?');
  };
  return (
    <>
      <Grid columnNum={5}>
        {goods &&
          goods
            .filter((it: GoodItem) => it.type == 'statusReurn')
            .map((i: GoodItem, index: number) => (
              <Grid.Item
                key={index}
                icon={<ShopO />}
                text={i.name + ' ' + i.size}
                onClick={() => statsuReturnFn(i)}
              />
            ))}
      </Grid>
    </>
  );
});
